<template>
  <div class="authentication-page">
    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="always" class="stat-card total-card">
            <el-statistic :value="breedingStats.totalApplications">
              <template #title>
                <div style="display: inline-flex; align-items: center">总申请数</div>
              </template>
              <template #suffix>
                <span style="font-size: 12px; color: #6b7280">+{{ breedingStats.newAddApplications }}本月</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="always" class="stat-card pending">
            <el-statistic :value="breedingStats.toBeCheckedApplications">
              <template #title>
                <div style="display: inline-flex; align-items: center">待审核</div>
              </template>
              <template #suffix>
                <span style="font-size: 12px; color: #6b7280">需要处理</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="always" class="stat-card supplement">
            <el-statistic :value="breedingStats.supplementApplications">
              <template #title>
                <div style="display: inline-flex; align-items: center">待补充</div>
              </template>
              <template #suffix>
                <span style="font-size: 12px; color: #6b7280">等待补充材料</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="filters-section">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="状态筛选:">
          <el-select
            v-model="searchOptions.statusList"
            style="width: 180px"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择状态"
            @change="handleSearch"
          >
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围:">
          <el-date-picker
            v-model="searchOptions.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="width: 250px"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchOptions.searchValue"
            placeholder="搜索申请人姓名或身份证号"
            style="width: 250px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-card>
        <div class="table-header">
          <h3>申请管理列表共{{ pagination.total }}条记录</h3>
          <el-button type="primary" plain @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>

        <el-table :data="tableData" height="500" style="width: 100%; margin-top: 10px">
          <el-table-column prop="name" label="申请人">
            <template #default="scope">
              <el-space>
                <el-avatar size="medium" :src="scope.row.avatar" />
                <span>{{ scope.row.name }}</span>
              </el-space>
            </template>
          </el-table-column>
          <el-table-column prop="idCard" label="身份证号">
            <template #default="scope">
              {{ scope.row.idCard }}
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" />
          <el-table-column prop="age" label="年龄" />
          <el-table-column prop="createTime" label="申请日期">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <div class="operation-buttons">
                <el-button size="small" @click="handleView(scope.row)"> 查看 </el-button>
                <el-button v-if="scope.row.status === 0" size="small" type="primary" @click="handleReview(scope.row)">
                  审核
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页部分 -->
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          style="margin-top: 20px"
          :page-sizes="[5, 10, 20, 30, 40]"
          size="default"
          layout="total, sizes, prev, pager, next"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 认证详情弹窗 -->
    <AuthenticationDetail v-model:visible="detailVisible" :data="selectedRecord" />

    <!-- 审核弹窗 -->
    <AuthenticationReview v-model:visible="reviewVisible" :data="reviewRecord" @submit="handleReviewSubmit" />
  </div>
</template>

<script setup lang="ts">
import {
  getAuthenticationDetail,
  getAuthenticationList,
  getBreedingStats,
  updateAuthentication,
} from '@/api/autentication';
import type { AuthenticationRequest, AuthenticationResponse, BreedingStats } from '@/api/model/authenticationModel';
import { formatDate } from '@/utils/date';
import { Refresh, Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, onActivated, ref, watch } from 'vue';

defineOptions({
  name: 'AuthenticationIndex',
});

// 动态导入组件
const AuthenticationDetail = defineAsyncComponent(() => import('../../components/AuthenticationDetail/index.vue'));
const AuthenticationReview = defineAsyncComponent(() => import('../../components/AuthenticationReview/index.vue'));

// 响应式数据
const loading = ref(false);

// 搜索表单
const searchForm = ref({});

// 搜索参数对象
const searchOptions = ref({
  searchValue: '',
  statusList: [],
  dateRange: [],
});

// 状态选项
const statusOptions = ref([
  { label: '待审核', value: 0 },
  { label: '已通过', value: 1 },
  { label: '已拒绝', value: 2 },
  { label: '待补充', value: 3 },
]);

// 表格数据
const tableData = ref<AuthenticationResponse[]>([]);
// 繁育统计数据
const breedingStats = ref<BreedingStats>({
  totalApplications: 0,
  toBeCheckedApplications: 0,
  passApplications: 0,
  rejectedApplications: 0,
  supplementApplications: 0,
  passRate: 0,
  rejectRate: 0,
  newAddApplications: 0,
});

// 详情弹窗相关
const detailVisible = ref(false);
const selectedRecord = ref<AuthenticationResponse | null>(null);

// 审核弹窗相关
const reviewVisible = ref(false);
const reviewRecord = ref<AuthenticationResponse | null>(null);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 状态相关方法
const getStatusText = (status: number) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    3: '待补充',
  };
  return statusMap[status] || '未知状态';
};

// Element Plus 标签类型映射
const getStatusType = (status: number) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info',
  };
  return typeMap[status] || 'default';
};

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(null, args), delay);
  };
};

// 获取繁育统计数据
const fetchBreedingStats = async () => {
  try {
    const response = await getBreedingStats();
    breedingStats.value = response.data.data;
  } catch (error) {
    console.error('获取繁育统计数据失败:', error);
    ElMessage.error(error.message || '获取统计数据失败');
  }
};

// 数据获取方法
const fetchData = async () => {
  try {
    loading.value = true;

    // 构建查询参数
    const params: AuthenticationRequest = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
    };

    // 添加状态筛选（支持多选）
    if (searchOptions.value.statusList && searchOptions.value.statusList.length > 0) {
      params.statusList = searchOptions.value.statusList;
    }

    // 添加时间范围筛选
    if (searchOptions.value.dateRange && searchOptions.value.dateRange.length === 2) {
      params.beginTime = searchOptions.value.dateRange[0] + ' 00:00:00';
      params.endTime = searchOptions.value.dateRange[1] + ' 00:00:00';
    }

    // 添加搜索关键词
    if (searchOptions.value.searchValue && searchOptions.value.searchValue.trim()) {
      params.searchValue = searchOptions.value.searchValue.trim();
    }

    // 调用API获取数据
    const response = await getAuthenticationList(params);
    tableData.value = response.data.data.records || [];
    pagination.value.total = response.data.data.total || 0;
  } catch (error: any) {
    console.error('获取认证申请列表失败:', error);
    ElMessage.error(error.message || '获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  pagination.value.current = 1; // 重置到第一页
  fetchData();
};

// 创建防抖的搜索函数
const debouncedSearch = debounce(handleSearch, 400);

// 分页大小变化处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  pagination.value.current = 1;
  fetchData();
};

// 当前页变化处理
const handleCurrentChange = (val: number) => {
  pagination.value.current = val;
  fetchData();
};

// 监听搜索条件变化，实现实时搜索
watch(
  [() => searchOptions.value.searchValue, () => searchOptions.value.statusList, () => searchOptions.value.dateRange],
  () => {
    // 使用防抖搜索
    debouncedSearch();
  },
  { deep: true },
);

// 页面加载时获取数据
onActivated(() => {
  fetchBreedingStats(); // 获取繁育统计数据
  fetchData(); // 获取列表数据
});

// 操作方法
const handleView = async (row: AuthenticationResponse) => {
  try {
    // 通过API获取详情数据
    const response = await getAuthenticationDetail(row.id);
    selectedRecord.value = response.data.data;
    detailVisible.value = true;
  } catch (error: any) {
    console.error('获取认证详情失败:', error);
    ElMessage.error(error.message || '获取详情失败');
  }
};

const handleReview = (row: AuthenticationResponse) => {
  reviewRecord.value = row;
  reviewVisible.value = true;
};

// 审核提交处理
const handleReviewSubmit = async (reviewData: any) => {
  try {
    loading.value = true;

    // 构建更新数据
    const updateData: AuthenticationRequest = {
      id: reviewRecord.value?.id,
      userId: reviewRecord.value?.userId,
      status: parseInt(reviewData.status), // 将字符串转换为数字
      checkOpinion: reviewData.checkOpinion,
    };

    // 调用更新API
    const response = await updateAuthentication(updateData);
    const res = response.data as any;
    if (res.code === 200) {
      ElMessage.success('审核成功');
      reviewVisible.value = false;

      // 刷新数据
      await fetchBreedingStats();
      await fetchData();
    } else {
      ElMessage.error(response.message || '审核失败');
    }
  } catch (error: any) {
    console.error('审核失败:', error);
    ElMessage.error(error.message || '审核失败');
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const handleRefresh = () => {
  pagination.value.current = 1;
  fetchBreedingStats(); // 刷新繁育统计数据
  fetchData(); // 刷新列表数据
};

// 重置筛选条件
const handleReset = () => {
  // 重置所有筛选条件
  searchOptions.value = {
    searchValue: '',
    statusList: [],
    dateRange: [],
  };

  // 重置分页到第一页
  pagination.value.current = 1;

  // 重新获取数据
  fetchData(); // 刷新列表数据
};
</script>

<style scoped lang="less">
.authentication-page {
  min-height: 100vh;

  // 统计卡片区域样式
  .stats-section {
    margin-bottom: 16px;

    .stat-card {
      height: 90px;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      // 总申请数卡片样式
      &.total-card {
        border-left: 4px solid #409eff;
      }

      // 待审核卡片样式
      &.pending {
        border-left: 4px solid #e6a23c;
      }

      // 待补充卡片样式
      &.supplement {
        border-left: 4px solid #909399;
      }
    }
  }

  // 筛选和搜索区域样式
  .filters-section {
    margin-bottom: 16px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .el-form {
      .el-form-item {
        margin-right: 20px;
        margin-bottom: 0;

        &:last-child {
          margin-right: 0;
        }

        .el-form-item__label {
          font-size: 14px;
          color: #6b7280;
          font-weight: 500;
        }
      }
    }
  }

  // 表格区域样式
  .table-section {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
      }
    }

    // 操作按钮样式
    .operation-buttons {
      display: flex;
      gap: 4px;
      flex-wrap: nowrap;
      align-items: center;

      .el-button {
        white-space: nowrap;
        min-width: auto;
      }
    }
  }
}
</style>
